<!DOCTYPE html>

<html>
  <head>
    <meta charset="utf-8">
    
    <title>numpy.polynomial.polynomial.polyfit &mdash; NumPy v1.18 Manual</title>
    
    <link rel="stylesheet" type="text/css" href="../../_static/css/spc-bootstrap.css">
    <link rel="stylesheet" type="text/css" href="../../_static/css/spc-extend.css">
    <link rel="stylesheet" href="../../_static/scipy.css" type="text/css" >
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" >
    <link rel="stylesheet" href="../../_static/graphviz.css" type="text/css" >
    
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../../',
        VERSION:     '1.18.1',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  false
      };
    </script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <script type="text/javascript" src="../../_static/js/copybutton.js"></script>
    <link rel="author" title="About these documents" href="../../about.html" >
    <link rel="index" title="Index" href="../../genindex.html" >
    <link rel="search" title="Search" href="../../search.html" >
    <link rel="top" title="NumPy v1.18 Manual" href="../../index.html" >
    <link rel="up" title="Polynomial Module (numpy.polynomial.polynomial)" href="../routines.polynomials.polynomial.html" >
    <link rel="next" title="numpy.polynomial.polynomial.polyvander" href="numpy.polynomial.polynomial.polyvander.html" >
    <link rel="prev" title="numpy.polynomial.polynomial.polyvalfromroots" href="numpy.polynomial.polynomial.polyvalfromroots.html" > 
  </head>
  <body>
<div class="container">
  <div class="top-scipy-org-logo-header" style="background-color: #a2bae8;">
    <a href="../../index.html">
      <img border=0 alt="NumPy" src="../../_static/numpy_logo.png"></a>
    </div>
  </div>
</div>


    <div class="container">
      <div class="main">
        
	<div class="row-fluid">
	  <div class="span12">
	    <div class="spc-navbar">
              
    <ul class="nav nav-pills pull-left">
        <li class="active"><a href="https://numpy.org/">NumPy.org</a></li>
        <li class="active"><a href="https://numpy.org/doc">Docs</a></li>
        
        <li class="active"><a href="../../index.html">NumPy v1.18 Manual</a></li>
        

          <li class="active"><a href="../index.html" >NumPy Reference</a></li>
          <li class="active"><a href="../routines.html" >Routines</a></li>
          <li class="active"><a href="../routines.polynomials.html" >Polynomials</a></li>
          <li class="active"><a href="../routines.polynomials.package.html" >Polynomial Package</a></li>
          <li class="active"><a href="../routines.polynomials.polynomial.html" accesskey="U">Polynomial Module (<code class="xref py py-mod docutils literal notranslate"><span class="pre">numpy.polynomial.polynomial</span></code>)</a></li> 
    </ul>
              
              
    <ul class="nav nav-pills pull-right">
      <li class="active">
        <a href="../../genindex.html" title="General Index"
           accesskey="I">index</a>
      </li>
      <li class="active">
        <a href="numpy.polynomial.polynomial.polyvander.html" title="numpy.polynomial.polynomial.polyvander"
           accesskey="N">next</a>
      </li>
      <li class="active">
        <a href="numpy.polynomial.polynomial.polyvalfromroots.html" title="numpy.polynomial.polynomial.polyvalfromroots"
           accesskey="P">previous</a>
      </li>
    </ul>
              
	    </div>
	  </div>
	</div>
        

	<div class="row-fluid">
      <div class="spc-rightsidebar span3">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="numpy.polynomial.polynomial.polyvalfromroots.html"
                        title="previous chapter">numpy.polynomial.polynomial.polyvalfromroots</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="numpy.polynomial.polynomial.polyvander.html"
                        title="next chapter">numpy.polynomial.polynomial.polyvander</a></p>
<div id="searchbox" style="display: none" role="search">
  <h4>Quick search</h4>
    <div>
    <form class="search" action="../../search.html" method="get">
      <input type="text" style="width: inherit;" name="q" />
      <input type="submit" value="search" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
          <div class="span9">
            
        <div class="bodywrapper">
          <div class="body" id="spc-section-body">
            
  <div class="section" id="numpy-polynomial-polynomial-polyfit">
<h1>numpy.polynomial.polynomial.polyfit<a class="headerlink" href="#numpy-polynomial-polynomial-polyfit" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="numpy.polynomial.polynomial.polyfit">
<code class="sig-prename descclassname">numpy.polynomial.polynomial.</code><code class="sig-name descname">polyfit</code><span class="sig-paren">(</span><em class="sig-param">x</em>, <em class="sig-param">y</em>, <em class="sig-param">deg</em>, <em class="sig-param">rcond=None</em>, <em class="sig-param">full=False</em>, <em class="sig-param">w=None</em><span class="sig-paren">)</span><a class="reference external" href="https://github.com/numpy/numpy/blob/v1.18.1/numpy/polynomial/polynomial.py#L1193-L1336"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#numpy.polynomial.polynomial.polyfit" title="Permalink to this definition">¶</a></dt>
<dd><p>Least-squares fit of a polynomial to data.</p>
<p>Return the coefficients of a polynomial of degree <em class="xref py py-obj">deg</em> that is the
least squares fit to the data values <em class="xref py py-obj">y</em> given at points <em class="xref py py-obj">x</em>. If <em class="xref py py-obj">y</em> is
1-D the returned coefficients will also be 1-D. If <em class="xref py py-obj">y</em> is 2-D multiple
fits are done, one for each column of <em class="xref py py-obj">y</em>, and the resulting
coefficients are stored in the corresponding columns of a 2-D return.
The fitted polynomial(s) are in the form</p>
<div class="math">
<p><img src="../../_images/math/61d112f6468fc9f1f1efaec41b3432614be009e1.svg" alt="p(x) = c_0 + c_1 * x + ... + c_n * x^n,"/></p>
</div><p>where <em class="xref py py-obj">n</em> is <em class="xref py py-obj">deg</em>.</p>
<dl class="field-list">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl>
<dt><strong>x</strong><span class="classifier">array_like, shape (<em class="xref py py-obj">M</em>,)</span></dt><dd><p>x-coordinates of the <em class="xref py py-obj">M</em> sample (data) points <code class="docutils literal notranslate"><span class="pre">(x[i],</span> <span class="pre">y[i])</span></code>.</p>
</dd>
<dt><strong>y</strong><span class="classifier">array_like, shape (<em class="xref py py-obj">M</em>,) or (<em class="xref py py-obj">M</em>, <em class="xref py py-obj">K</em>)</span></dt><dd><p>y-coordinates of the sample points.  Several sets of sample points
sharing the same x-coordinates can be (independently) fit with one
call to <a class="reference internal" href="#numpy.polynomial.polynomial.polyfit" title="numpy.polynomial.polynomial.polyfit"><code class="xref py py-obj docutils literal notranslate"><span class="pre">polyfit</span></code></a> by passing in for <em class="xref py py-obj">y</em> a 2-D array that contains
one data set per column.</p>
</dd>
<dt><strong>deg</strong><span class="classifier">int or 1-D array_like</span></dt><dd><p>Degree(s) of the fitting polynomials. If <em class="xref py py-obj">deg</em> is a single integer
all terms up to and including the <em class="xref py py-obj">deg</em>’th term are included in the
fit. For NumPy versions &gt;= 1.11.0 a list of integers specifying the
degrees of the terms to include may be used instead.</p>
</dd>
<dt><strong>rcond</strong><span class="classifier">float, optional</span></dt><dd><p>Relative condition number of the fit.  Singular values smaller
than <em class="xref py py-obj">rcond</em>, relative to the largest singular value, will be
ignored.  The default value is <code class="docutils literal notranslate"><span class="pre">len(x)*eps</span></code>, where <em class="xref py py-obj">eps</em> is the
relative precision of the platform’s float type, about 2e-16 in
most cases.</p>
</dd>
<dt><strong>full</strong><span class="classifier">bool, optional</span></dt><dd><p>Switch determining the nature of the return value.  When <code class="docutils literal notranslate"><span class="pre">False</span></code>
(the default) just the coefficients are returned; when <code class="docutils literal notranslate"><span class="pre">True</span></code>,
diagnostic information from the singular value decomposition (used
to solve the fit’s matrix equation) is also returned.</p>
</dd>
<dt><strong>w</strong><span class="classifier">array_like, shape (<em class="xref py py-obj">M</em>,), optional</span></dt><dd><p>Weights. If not None, the contribution of each point
<code class="docutils literal notranslate"><span class="pre">(x[i],y[i])</span></code> to the fit is weighted by <em class="xref py py-obj">w[i]</em>. Ideally the
weights are chosen so that the errors of the products <code class="docutils literal notranslate"><span class="pre">w[i]*y[i]</span></code>
all have the same variance.  The default value is None.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 1.5.0.</span></p>
</div>
</dd>
</dl>
</dd>
<dt class="field-even">Returns</dt>
<dd class="field-even"><dl>
<dt><strong>coef</strong><span class="classifier">ndarray, shape (<em class="xref py py-obj">deg</em> + 1,) or (<em class="xref py py-obj">deg</em> + 1, <em class="xref py py-obj">K</em>)</span></dt><dd><p>Polynomial coefficients ordered from low to high.  If <em class="xref py py-obj">y</em> was 2-D,
the coefficients in column <em class="xref py py-obj">k</em> of <em class="xref py py-obj">coef</em> represent the polynomial
fit to the data in <em class="xref py py-obj">y</em>’s <em class="xref py py-obj">k</em>-th column.</p>
</dd>
<dt><strong>[residuals, rank, singular_values, rcond]</strong><span class="classifier">list</span></dt><dd><p>These values are only returned if <em class="xref py py-obj">full</em> = True</p>
<p>resid – sum of squared residuals of the least squares fit
rank – the numerical rank of the scaled Vandermonde matrix
sv – singular values of the scaled Vandermonde matrix
rcond – value of <em class="xref py py-obj">rcond</em>.</p>
<p>For more details, see <em class="xref py py-obj">linalg.lstsq</em>.</p>
</dd>
</dl>
</dd>
<dt class="field-odd">Raises</dt>
<dd class="field-odd"><dl>
<dt><strong>RankWarning</strong></dt><dd><p>Raised if the matrix in the least-squares fit is rank deficient.
The warning is only raised if <em class="xref py py-obj">full</em> == False.  The warnings can
be turned off by:</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">warnings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s1">&#39;ignore&#39;</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">RankWarning</span><span class="p">)</span>
</pre></div>
</div>
</dd>
</dl>
</dd>
</dl>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p><code class="xref py py-obj docutils literal notranslate"><span class="pre">chebfit</span></code>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">legfit</span></code>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">lagfit</span></code>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">hermfit</span></code>, <code class="xref py py-obj docutils literal notranslate"><span class="pre">hermefit</span></code></p>
<dl class="simple">
<dt><a class="reference internal" href="numpy.polynomial.polynomial.polyval.html#numpy.polynomial.polynomial.polyval" title="numpy.polynomial.polynomial.polyval"><code class="xref py py-obj docutils literal notranslate"><span class="pre">polyval</span></code></a></dt><dd><p>Evaluates a polynomial.</p>
</dd>
<dt><a class="reference internal" href="numpy.polynomial.polynomial.polyvander.html#numpy.polynomial.polynomial.polyvander" title="numpy.polynomial.polynomial.polyvander"><code class="xref py py-obj docutils literal notranslate"><span class="pre">polyvander</span></code></a></dt><dd><p>Vandermonde matrix for powers.</p>
</dd>
<dt><code class="xref py py-obj docutils literal notranslate"><span class="pre">linalg.lstsq</span></code></dt><dd><p>Computes a least-squares fit from the matrix.</p>
</dd>
<dt><a class="reference external" href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.UnivariateSpline.html#scipy.interpolate.UnivariateSpline" title="(in SciPy v1.4.1)"><code class="xref py py-obj docutils literal notranslate"><span class="pre">scipy.interpolate.UnivariateSpline</span></code></a></dt><dd><p>Computes spline fits.</p>
</dd>
</dl>
</div>
<p class="rubric">Notes</p>
<p>The solution is the coefficients of the polynomial <em class="xref py py-obj">p</em> that minimizes
the sum of the weighted squared errors</p>
<div class="math">
<p><img src="../../_images/math/561c9a302473d41c77e11d4512d5d9365ee5de22.svg" alt="E = \sum_j w_j^2 * |y_j - p(x_j)|^2,"/></p>
</div><p>where the <img class="math" src="../../_images/math/52cb7e0ee86d8a0b7ff7e68a1db495bd058d8198.svg" alt="w_j"/> are the weights. This problem is solved by
setting up the (typically) over-determined matrix equation:</p>
<div class="math">
<p><img src="../../_images/math/fa1933754de9f1755d11f388c622a82ffbb42e6a.svg" alt="V(x) * c = w * y,"/></p>
</div><p>where <em class="xref py py-obj">V</em> is the weighted pseudo Vandermonde matrix of <em class="xref py py-obj">x</em>, <em class="xref py py-obj">c</em> are the
coefficients to be solved for, <em class="xref py py-obj">w</em> are the weights, and <em class="xref py py-obj">y</em> are the
observed values.  This equation is then solved using the singular value
decomposition of <em class="xref py py-obj">V</em>.</p>
<p>If some of the singular values of <em class="xref py py-obj">V</em> are so small that they are
neglected (and <em class="xref py py-obj">full</em> == <code class="docutils literal notranslate"><span class="pre">False</span></code>), a <em class="xref py py-obj">RankWarning</em> will be raised.
This means that the coefficient values may be poorly determined.
Fitting to a lower order polynomial will usually get rid of the warning
(but may not be what you want, of course; if you have independent
reason(s) for choosing the degree which isn’t working, you may have to:
a) reconsider those reasons, and/or b) reconsider the quality of your
data).  The <em class="xref py py-obj">rcond</em> parameter can also be set to a value smaller than
its default, but the resulting fit may be spurious and have large
contributions from roundoff error.</p>
<p>Polynomial fits using double precision tend to “fail” at about
(polynomial) degree 20. Fits using Chebyshev or Legendre series are
generally better conditioned, but much can still depend on the
distribution of the sample points and the smoothness of the data.  If
the quality of the fit is inadequate, splines may be a good
alternative.</p>
<p class="rubric">Examples</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">numpy.polynomial</span> <span class="kn">import</span> <span class="n">polynomial</span> <span class="k">as</span> <span class="n">P</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">linspace</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">51</span><span class="p">)</span> <span class="c1"># x &quot;data&quot;: [-1, -0.96, ..., 0.96, 1]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">**</span><span class="mi">3</span> <span class="o">-</span> <span class="n">x</span> <span class="o">+</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">))</span> <span class="c1"># x^3 - x + N(0,1) &quot;noise&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">,</span> <span class="n">stats</span> <span class="o">=</span> <span class="n">P</span><span class="o">.</span><span class="n">polyfit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="n">full</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="c1"># c[0], c[2] should be approx. 0, c[1] approx. -1, c[3] approx. 1</span>
<span class="go">array([ 0.01909725, -1.30598256, -0.00577963,  1.02644286]) # may vary</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span> <span class="c1"># note the large SSR, explaining the rather poor results</span>
<span class="go"> [array([ 38.06116253]), 4, array([ 1.38446749,  1.32119158,  0.50443316, # may vary</span>
<span class="go">          0.28853036]), 1.1324274851176597e-014]</span>
</pre></div>
</div>
<p>Same thing without the added noise</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="o">**</span><span class="mi">3</span> <span class="o">-</span> <span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">,</span> <span class="n">stats</span> <span class="o">=</span> <span class="n">P</span><span class="o">.</span><span class="n">polyfit</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="n">full</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="c1"># c[0], c[2] should be &quot;very close to 0&quot;, c[1] ~= -1, c[3] ~= 1</span>
<span class="go">array([-6.36925336e-18, -1.00000000e+00, -4.08053781e-16,  1.00000000e+00])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span> <span class="c1"># note the minuscule SSR</span>
<span class="go">[array([  7.46346754e-31]), 4, array([ 1.38446749,  1.32119158, # may vary</span>
<span class="go">           0.50443316,  0.28853036]), 1.1324274851176597e-014]</span>
</pre></div>
</div>
</dd></dl>

</div>


          </div>
        </div>
          </div>
        </div>
      </div>
    </div>

    <div class="container container-navbar-bottom">
      <div class="spc-navbar">
        
      </div>
    </div>
    <div class="container">
    <div class="footer">
    <div class="row-fluid">
    <ul class="inline pull-left">
      <li>
        &copy; Copyright 2008-2019, The SciPy community.
      </li>
      <li>
      Last updated on Feb 20, 2020.
      </li>
      <li>
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.4.2.
      </li>
    </ul>
    </div>
    </div>
    </div>
  </body>
</html>